package com.nassir.chatroom.util;

import java.util.List;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.nassir.chatroom.constant.Constant;

/**
 * @Title: Configuration.java
 * @Description: 系统参数配置工具类
 * @Author Nassir wen
 * @Date 2011-3-14 上午09:55:47
 * @Copyright Copyright (c) 2010
 */
public class DynamicConfig {
	private static final Log logger = LogFactory.getLog(DynamicConfig.class);

	private static DynamicConfig _instance = null;

	private String configPath = "config.properties";

	private static PropertiesConfiguration propConfig = null;
	/** 监听时间,每5分钟加载一次 */
	private static long refreshDelay = 1 * 5 * 60 * 1000;

	private DynamicConfig() {
		logger.info("init...");
		try {
			propConfig = new PropertiesConfiguration(configPath);
			FileChangedReloadingStrategy reloadStrategy = new FileChangedReloadingStrategy();
			reloadStrategy.setRefreshDelay(refreshDelay);
			propConfig.setReloadingStrategy(reloadStrategy);
		} catch (ConfigurationException e) {
			logger.error("系统配置文件不存在!", e);
		}
	}

	public static DynamicConfig getInstance() {
		if (_instance == null) {
			_instance = new DynamicConfig();
		}
		return _instance;
	}

	/**
	 * 获取系统配置参数
	 * 
	 * @param key
	 * @return
	 */
	public String getValue(String key) {
		return getValue(key, "");
	}

	/**
	 * 获取系统配置参数
	 * 
	 * @param key
	 * @param defaultValue
	 *            如果没有找到参数值,则返回此默认值
	 * @return
	 */
	public String getValue(String key, String defaultValue) {
		return propConfig.getString(key, defaultValue);
	}

	/**
	 * 获取系统配置参数
	 * 
	 * @param key
	 * @return
	 */
	public int getInt(String key) {
		return getInt(key, 0);
	}

	/**
	 * 获取系统配置参数
	 * 
	 * @param key
	 * @param defaultValue
	 *            如果没有找到参数值,则返回此默认值
	 * @return
	 */
	public int getInt(String key, int defaultValue) {
		return propConfig.getInt(key, defaultValue);
	}

	/**
	 * 例： colors.pie = #FF0000, #00FF00, #0000FF List colorList =
	 * config.getList("colors.pie"); 获取系统配置参数
	 * 
	 * @param key
	 * @return 返回
	 */
	@SuppressWarnings("unchecked")
	public List<String> getList(String key) {
		return propConfig.getList(key);
	}

	public static void main(String[] args) {
		System.out.println(DynamicConfig.getInstance().getValue(
				Constant.SERVER_ADDR)
				+ ":"
				+ DynamicConfig.getInstance().getInt(Constant.SERVER_PORT));
		System.out.println();
	}
}
